import QRCode from '../../utils/weapp-qrcode.js'
const base64 = require('../../utils/base64.js')
const app = getApp()
Page({
	data: {
		interval: 1,
		times: 1
	},
	makecanvas(){
		if(!this.canvas){
			this.canvas = new QRCode('canvas', {
				text: base64.encode('rule|'+this.data._id),
				padding: 12,
				width: this.data.qrcode_w,
				height: this.data.qrcode_w,
				correctLevel: QRCode.CorrectLevel.H,
				callback: (res) => {
					// 生成二维码的临时文件
					this.setData({
						qrcode: res.path
					})
					console.log(res.path)
				}
			});
		}
	},
	onLoad: function (options) {
		this.setData(options)
		this.setData({
			qrcode_w: app.globalData.qrcode_w
		})

		if (options._id) {
			wx.setNavigationBarTitle({
				title: '编辑规则',
			})
			app.db.collection('code').doc(options._id).get().then(res=>{
				this.setData(res.data)
				this.makecanvas()
			})
			
		}
	},
	changeValue(e) {
		this.setData({
			[e.currentTarget.dataset.key]: e.detail.value
		})
	},
	onSubmit(e) {
		let data = e.detail.value
		if (!data.name) {
			return wx.showToast({
				title: '请输入名称',
				icon: 'none'
			})
		}
		if(this.data._id){
			data._id = this.data._id
		}
		data.interval = this.data.interval
		data.times = this.data.times
		data.shop_id = this.data.shop_id
		app.cloud({
			name: 'shopCode',
			data,
			loading: '提交中',
			def: true,
			success: res => {
				wx.showToast({
					title: res.msg,
				})
				//读取db
				app.db.collection('code').doc(res.data).get().then(res=>{
					console.log(res)
					this.setData(res.data)
					this.makecanvas()
				})
			}
		})
	},
	save(){
		wx.saveImageToPhotosAlbum({
		  filePath: this.data.qrcode,
		})
	},
	showQrcode(){
		wx.previewImage({
		  urls: [this.data.qrcode],
		})
	}
})